package grpc

import (
	"fmt"
	"gitee.com/xiao_hange/go-admin-pkg/pkg/grpcx/interceptors/trace"
	"go-admin/server/ioc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/resolver"
)

type config struct {
	Secure        bool
	Name          string
	ServiceConfig string
}

func InitGrpcClient(rb resolver.Builder, typeAddr, serviceName string, cfg config) (*grpc.ClientConn, error) {
	tracerProvider := ioc.InitOTELTracerProvider()
	otelBuilder := trace.NewOTELInterceptorBuilder(serviceName, tracerProvider.Tracer(serviceName), nil)
	otelClientInterceptor := otelBuilder.BuildUnaryClientInterceptor()
	opts := []grpc.DialOption{
		grpc.WithResolvers(rb),                           //gRPC 客户端连接的解析器
		grpc.WithDefaultServiceConfig(cfg.ServiceConfig), //负载均衡
		grpc.WithUnaryInterceptor(
			otelClientInterceptor,
		), //拦截器
	}

	if cfg.Secure {
		// 上面，要去加载你的证书之类的东西
		// 启用 HTTPS
	} else {
		opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	}

	cc, err := grpc.Dial(fmt.Sprintf("%s:///%s", typeAddr, cfg.Name), opts...)
	if err != nil {
		return nil, err
	}
	return cc, nil
}
